//
//  HMUserAccountViewModel.swift
//  sina
//
//  Created by Kent on 16/9/26.
//  Copyright © 2016年 Ming. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {

    static let sharedAccountViewModel: HMUserAccountViewModel = HMUserAccountViewModel()
    
    var userAccount: HMUserAccount? {
        didSet {
            let urlString = userAccount?.avatar_large ?? ""
            iconUrl = URL(string: urlString)
        }
    }
    
    var iconUrl: URL?
    
    var userLogin: Bool {
        
        if userAccount?.access_token != nil && isExpired == false {
            return true
        }
        
        return false
    }
    
    var isExpired: Bool {
        
        if userAccount?.expired_date?.compare(Date()) == ComparisonResult.orderedDescending {
            return false
        }
        
        return true
    }
    
    override init() {
        super.init()
        self.userAccount = self.loadUserAccount()
        
        iconUrl = URL(string: userAccount?.avatar_large ?? "")
    }
    
    internal func loadAccessToken(code: String, finished: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri": redirect_uri]
        
        HMNetworkTools.sharedTool.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            
            if error != nil {
                finished(false)
                return
            }
        
            self.loadUserInfo(dict: responseObject as! [String : Any],finished: finished)
            
        }
        
    }
    
    private func loadUserInfo(dict: [String : Any], finished: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        //"https://api.weibo.com/2/users/show.json"
        
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        
        HMNetworkTools.sharedTool.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            
            if error != nil {
                finished(false)
                return
            }
            
            var userInfoDict = responseObject as! [String : Any]
            
            for keyValues in dict {
                userInfoDict[keyValues.key] = keyValues.value
            }
            
            let userAccount = HMUserAccount(dict: userInfoDict)
            
            self.saveUserAccount(userAccount: userAccount)
            
            self.userAccount = userAccount
            
            finished(true)
        }
        
    }
    
    private func saveUserAccount(userAccount: HMUserAccount) {
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
        
    }
    
    private func loadUserAccount() -> HMUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccount
        return userAccount
    }

}
